package io.rong.imkit.conversation;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.custom.base.config.BaseConfig;
import com.custom.base.util.SystemUtil;

import io.rong.imkit.R;
import io.rong.imkit.activity.RongBaseActivity;
import io.rong.imkit.http.HttpRequest;
import io.rong.imkit.model.TypingInfo;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.userinfo.model.GroupUserInfo;
import io.rong.imkit.utils.LocationUtils;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imkit.widget.TitleBar;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

import java.util.Locale;

public class RongConversationActivity extends RongBaseActivity {
    protected String mTargetId;
    protected Conversation.ConversationType mConversationType;
    protected ConversationFragment mConversationFragment;
    private ConversationViewModel conversationViewModel;
    private int blackFlag = 0;
    private LinearLayout userBlackContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        if (getIntent() != null) {
            mTargetId = getIntent().getStringExtra(RouteUtils.TARGET_ID);
            String type = getIntent().getStringExtra(RouteUtils.CONVERSATION_TYPE);
            if (!TextUtils.isEmpty(type)) {
                mConversationType =
                        Conversation.ConversationType.valueOf(type.toUpperCase(Locale.US));
            } else {
                return;
            }
        }
        setContentView(R.layout.rc_conversation_activity);
        setTitle();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            blackFlag = bundle.getInt("blackFlag", 0);
        }
        userBlackContainer = findViewById(R.id.user_black_container);
        userBlackContainer.setVisibility(blackFlag == 1 ? View.VISIBLE : View.GONE);
        mConversationFragment =
                (ConversationFragment)
                        getSupportFragmentManager().findFragmentById(R.id.conversation);
        mTitleBar.setOnBackClickListener(
                new TitleBar.OnBackClickListener() {
                    @Override
                    public void onBackClick() {
                        if (mConversationFragment != null
                                && !mConversationFragment.onBackPressed()) {
                            finish();
                        }
                    }
                });
        mTitleBar.getRightView().setVisibility(View.GONE);
        mTitleBar.setMoreViewVisibility(!BaseConfig.Companion.getGetInstance().getString("serverUserCode", "").equals(mTargetId));
        mTitleBar.setOnRightMoreClickListener(new TitleBar.OnRightIconClickListener() {
            @Override
            public void onRightIconClick(View v) {
                if (mConversationFragment != null) {
                    mConversationFragment.onMoreClick();
                }
            }
        });
        mTitleBar.setOnTitleClickListener(v -> {
            if (mConversationFragment != null) {
                mConversationFragment.onTitleClick();
            }
        });
        initViewModel();
        observeUserInfoChange();

        HttpRequest.INSTANCE.getUserModelInfo(mTargetId, entity -> {
            String nickName = entity.getData().getUserAccount().getNickName();
            nickName = nickName.length() > 10 ? nickName.substring(0, 10) + "..." : nickName;
            if (entity.getData().getMember()) {
                SpannableStringBuilder style = new SpannableStringBuilder();
                String startString =nickName + " , " + entity.getData().getUserAccount().getAge();
                style.append(startString);
                style.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View view) {

                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        ds.setUnderlineText(false);
                        ds.setColor(Color.parseColor("#FAC44E"));
                        ds.clearShadowLayer();
                    }
                }, 0, nickName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                String city ="";
                if (entity.getData().getUserAccount().getLat() != null && entity.getData().getUserAccount().getLng()!= null){
                    if (entity.getData().getUserAccount().getLat() != 0.0 && entity.getData().getUserAccount().getLng()!= 0.0) {
                        city = new LocationUtils().getCity(this, entity.getData().getUserAccount().getLat(), entity.getData().getUserAccount().getLng());
                    }
                }
                if (!city.equals("")){
                    style.append(" , " + city);
                    style.setSpan(new ClickableSpan() {
                        @Override
                        public void onClick(@NonNull View view) {

                        }

                        @Override
                        public void updateDrawState(@NonNull TextPaint ds) {
                            ds.setUnderlineText(false);
                            ds.setColor(Color.BLACK);
//                            ds.setColor(entity.getData().getUserAccount().getOpenLocation()?Color.BLACK:Color.parseColor("#D9D9D9"));
                            ds.clearShadowLayer();
                        }
                    }, startString.length()+3, startString.length()+3+city.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                mTitleBar.getMiddleView().setText(style);
                mTitleBar.getMiddleView().setMovementMethod(LinkMovementMethod.getInstance());

                Drawable drawable = ContextCompat.getDrawable(getBaseContext(), R.drawable.icon_profile_crown);
                int drawableWidth = 19;
                int drawableHeight = 14;
                drawable.setBounds(0, 0, drawableWidth, drawableHeight);
                mTitleBar.getMiddleView().setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            } else {
                SpannableStringBuilder style = new SpannableStringBuilder();
                String startString =nickName + " , " + entity.getData().getUserAccount().getAge();
                style.append(startString);
                String city ="";
                if (entity.getData().getUserAccount().getLat() != null && entity.getData().getUserAccount().getLng()!= null){
                    if (entity.getData().getUserAccount().getLat() != 0.0 && entity.getData().getUserAccount().getLng()!= 0.0) {
                        city = new LocationUtils().getCity(this, entity.getData().getUserAccount().getLat(), entity.getData().getUserAccount().getLng());
                    }
                }
                if (!city.equals("")){
                    style.append(" , " + city);
                }
                mTitleBar.getMiddleView().setText(style);
                mTitleBar.getMiddleView().setMovementMethod(LinkMovementMethod.getInstance());
            }
            mTitleBar.getLastTimeView().setText(entity.getData().getUserAccount().getLocalTime());
            mTitleBar.getLevelView().setText("Lv" + entity.getData().getUserAccount().getLevel());
            switch (entity.getData().getUserAccount().getLevel()) {
                case 0:
                    mTitleBar.getLevelView().setBackgroundResource(R.drawable.shape_im_user_level_one);
                    break;
                case 1:
                case 2:
                case 3:
                    mTitleBar.getLevelView().setBackgroundResource(R.drawable.shape_im_user_level_two);
                    break;
                case 4:
                case 5:
                case 6:
                    mTitleBar.getLevelView().setBackgroundResource(R.drawable.shape_im_user_level_three);
                    break;
                case 7:
                case 8:
                case 9:
                    mTitleBar.getLevelView().setBackgroundResource(R.drawable.shape_im_user_level_four);
                    break;
                case 10:
                    mTitleBar.getLevelView().setBackgroundResource(R.drawable.shape_im_user_level_five);
                    break;
                default:
                    break;
            }

        });
    }

    private void observeUserInfoChange() {
        if (!TextUtils.isEmpty(mTargetId)) {
            RongUserInfoManager.getInstance().addUserDataObserver(mUserDataObserver);
        }
    }

    private final RongUserInfoManager.UserDataObserver mUserDataObserver =
            new RongUserInfoManager.UserDataObserver() {
                @Override
                public void onUserUpdate(UserInfo info) {
                    if (TextUtils.equals(mTargetId, info.getUserId())) {
                        runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        setTitle();
                                    }
                                });
                    }
                }

                @Override
                public void onGroupUpdate(Group group) {
                    if (TextUtils.equals(mTargetId, group.getId())) {
                        runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        setTitle();
                                    }
                                });
                    }
                }

                @Override
                public void onGroupUserInfoUpdate(GroupUserInfo groupUserInfo) {
                    // do nothing
                }
            };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!TextUtils.isEmpty(mTargetId)) {
            RongUserInfoManager.getInstance().removeUserDataObserver(mUserDataObserver);
        }
    }

    private void setTitle() {
//        if (!TextUtils.isEmpty(mTargetId)
//                && mConversationType.equals(Conversation.ConversationType.GROUP)) {
//            Group group = RongUserInfoManager.getInstance().getGroupInfo(mTargetId);
//            mTitleBar.setTitle(group == null ? mTargetId : group.getName());
//        } else {
//            UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(mTargetId);
//            mTitleBar.setTitle(userInfo == null ? mTargetId : userInfo.getName());
//        }
        //只显示Name，不显示TargetId
        if (!TextUtils.isEmpty(mTargetId)
                && mConversationType.equals(Conversation.ConversationType.GROUP)) {
            Group group = RongUserInfoManager.getInstance().getGroupInfo(mTargetId);
            mTitleBar.setTitle(group == null ? "" : group.getName());
        } else {
            UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(mTargetId);
            mTitleBar.setTitle(userInfo == null ? "" : userInfo.getName());
        }
        if (mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE)
                || mConversationType.equals(Conversation.ConversationType.CHATROOM)) {
            mTitleBar.setRightVisible(false);
        }
    }

    private void initViewModel() {
        conversationViewModel = new ViewModelProvider(this).get(ConversationViewModel.class);
        conversationViewModel
                .getTypingStatusInfo()
                .observe(
                        this,
                        new Observer<TypingInfo>() {
                            @Override
                            public void onChanged(TypingInfo typingInfo) {
                                if (typingInfo == null) {
                                    return;
                                }
//                                if (typingInfo.conversationType == mConversationType
//                                        && mTargetId.equals(typingInfo.targetId)) {
//                                    if (typingInfo.typingList == null) {
//                                        mTitleBar.getMiddleView().setVisibility(View.VISIBLE);
//                                        mTitleBar.getTypingView().setVisibility(View.GONE);
//                                    } else {
//                                        mTitleBar.getMiddleView().setVisibility(View.GONE);
//                                        mTitleBar.getTypingView().setVisibility(View.VISIBLE);
//                                        TypingInfo.TypingUserInfo typing =
//                                                typingInfo.typingList.get(
//                                                        typingInfo.typingList.size() - 1);
//                                        if (typing.type == TypingInfo.TypingUserInfo.Type.text) {
//                                            mTitleBar.setTyping(
//                                                    R.string.rc_conversation_remote_side_is_typing);
//                                        } else if (typing.type
//                                                == TypingInfo.TypingUserInfo.Type.voice) {
//                                            mTitleBar.setTyping(
//                                                    R.string.rc_conversation_remote_side_speaking);
//                                        }
//                                    }
//                                }
                            }
                        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
            if (mConversationFragment != null && !mConversationFragment.onBackPressed()) {
                finish();
            }
        }
        return false;
    }
}
